package yxy.game.pm2.command.hero;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Hero;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.HeroMessage;
import yxy.game.pm2.module.hero.HeroHandle;
import yxy.game.pm2.module.resonate.ResonateHandle;

@MessageType(proto = Command.HeroStageUp, classtype = HeroMessage.HeroStageUpRequest.class)
public class CMD_HeroStageUp extends Command<HeroMessage.HeroStageUpRequest> {

	@Override
	public void execute(MessageSource messageSource, HeroMessage.HeroStageUpRequest request) {
		String playerCode = messageSource.getTag();
		String code = request.getCode();

		HeroMessage.HeroStageUpResponse.Builder response = HeroMessage.HeroStageUpResponse.newBuilder();

		try {
			if (Hero.lockHero(playerCode)) {

				HeroHandle heroHandle = new HeroHandle();
				Hero hero = heroHandle.getHero(playerCode, code);
				if (hero == null) {
					send(messageSource, response, Result.ParamError);
					return;
				}

				//共鸣的武将不能升阶
				Result resultForResonate = ResonateHandle.heroIsResonateHero(hero, playerCode);
				if(!resultForResonate.equals(Result.Success)){
					send(messageSource, response, resultForResonate);
					return;
				}

				Result result = heroHandle.stageUp(playerCode, hero);
				if (!result.equals(Result.Success)) {
					send(messageSource, response, result);
					return;
				}
				HeroMessage.HeroInfo heroInfo = heroHandle.getHeroInfo(playerCode, hero);
				response.setInfo(heroInfo);
				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			Hero.unlockHero(playerCode);
		}
	}

	private void send(MessageSource messageSource, HeroMessage.HeroStageUpResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}

}
